package com.ruoyi.central.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.cache.common.CacheConstants;
import com.ruoyi.central.domain.TopCentralProductRelation;
import com.ruoyi.central.domain.TopCentralTaskCmd;
import com.ruoyi.central.publisher.PublisherUtils;
import com.ruoyi.central.publisher.event.TaskCmdRunEvent;
import com.ruoyi.central.service.ITopCentralTaskCmdService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.SignEnum;
import com.ruoyi.common.enums.common.TaskStatusEnum;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.PageHelperUtils;
import com.ruoyi.common.utils.service.ServiceUtils;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.service.ServiceImpl;
import com.ruoyi.central.mapper.TopCentralTaskCmdRunMapper;
import com.ruoyi.central.domain.TopCentralTaskCmdRun;
import com.ruoyi.central.service.ITopCentralTaskCmdRunService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.enums.common.State;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;

/**
 * 任务执行指令Service业务层处理
 *
 * @author SunLuQuan
 * @date 2022-05-29
 */
@Service
@Slf4j
@CacheConfig(cacheNames = CacheConstants.EhcacheName.CONTINUAL_CACHE_NAME)
public class TopCentralTaskCmdRunServiceImpl extends ServiceImpl<TopCentralTaskCmdRunMapper,TopCentralTaskCmdRun> implements ITopCentralTaskCmdRunService
{
    @Autowired
    private ITopCentralTaskCmdService taskCmdService;
    /**
     * 查询任务执行指令
     * 
     * @param id 任务执行指令主键
     * @param columns 查询指定的列
     * @return 任务执行指令
     */
    @Override
    public TopCentralTaskCmdRun selectById(Integer id, SFunction<TopCentralTaskCmdRun,?> ... columns){

        if(StringUtils.isNotEmpty(columns)){
            return selectOne(lambdaQuery().select(columns).eq(TopCentralTaskCmdRun::getId,id));
        }
        return super.selectById(id);
    }

    /**
     * 查询任务执行指令
         * 注意：只获取状态信息为可用的数据
     * 
     * @param id 任务执行指令主键
     * @param columns 查询指定的列
     * @return 任务执行指令
     */
    @Override
    public TopCentralTaskCmdRun selectUsableById(Integer id, SFunction<TopCentralTaskCmdRun,?> ... columns)
    {
            LambdaQueryWrapper<TopCentralTaskCmdRun> lambdaQueryWrapper = lambdaQuery().eq(TopCentralTaskCmdRun::getId,id);
            buildUsableState(lambdaQueryWrapper);
            if(StringUtils.isNotEmpty(columns)){
                lambdaQueryWrapper.select(columns);
            }
            return selectOne(lambdaQueryWrapper);
    }

    /**
     * 查询任务执行指令列表
     *
     * @param topCentralTaskCmdRun 任务执行指令
     * @return 任务执行指令
     */
    @Override
    public List<TopCentralTaskCmdRun> selectList(TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        return getBaseMapper().selectTopCentralTaskCmdRunList(topCentralTaskCmdRun);
    }

    /**
     * 根据工序执行对象编号 获取最近一个完成的执行指令任务的下一个任务
     * @param activeProcessStepRunId 工序执行对象编号
     * @return
     */
    @Override
    public TopCentralTaskCmdRun getFinishedNextByProcessStepRunId(Integer activeProcessStepRunId) {

        PageHelperUtils.startPageOfSingle();

        LambdaQueryWrapper<TopCentralTaskCmdRun> lambdaQueryWrapper =
                customLambdaQuery()
                .eq(TopCentralTaskCmdRun::getProcessStepRunId, activeProcessStepRunId)
                .ne(TopCentralTaskCmdRun::getTaskStatus,TaskStatusEnum.EXECUTED_FINISH)
                .orderByAsc(TopCentralTaskCmdRun::getWeight);

        return selectOne(lambdaQueryWrapper);
    }

    /**
     * 根据工序执行编号 获取当前工序执行下所有的 执行指令列表
     * @param activeProcessStepRunId
     * @return
     */
    @Override
    public List<TopCentralTaskCmdRun> selectByProcessStepRunId(Integer activeProcessStepRunId) {
        TopCentralTaskCmdRun params = new TopCentralTaskCmdRun();
        params.setProcessStepRunId(activeProcessStepRunId);

        List<TopCentralTaskCmdRun> taskCmdRuns = selectSimpleList(params);

        if(StringUtils.isNotEmpty(taskCmdRuns)){

            ServiceUtils.complete(taskCmdRuns,taskCmdService,((taskCmdMap, taskCmdRun) -> {
                taskCmdRun.setTaskCmd(taskCmdMap.get(taskCmdRun.getTaskCmdId()));
            }));

            taskCmdRuns.sort(Comparator.comparing(TopCentralTaskCmdRun::getWeight));
        }
        return taskCmdRuns;
    }

    /**
     * 判断当前执行工序下的 所有执行指令是否完成
     * @param activeProcessStepRunId 执行工序编号
     * @return false 有未完成的 true 无未完成的
     */
    @Override
    public boolean isTaskCmdRunFinishedByProcessStepRunId(Integer activeProcessStepRunId) {

        Long notFinishedCount = getBaseMapper().selectCount(customLambdaQuery().eq(TopCentralTaskCmdRun::getProcessStepRunId, activeProcessStepRunId)
                .ne(TopCentralTaskCmdRun::getTaskStatus, TaskStatusEnum.EXECUTED_FINISH));
        if(StringUtils.isNotNull(notFinishedCount) && notFinishedCount == 0){
            return true;
        }
        return false;
    }

    /**
     * 获取所有的任务执行指令数据
     * 
     * @return Map<Integer,TopCentralTaskCmdRun> 集合
     */
    @Cacheable
    @Override
    public Map<Integer,TopCentralTaskCmdRun> selectAllMap(){

        return selectSimpleList(customLambdaQuery())
                .stream().collect(Collectors.toMap(TopCentralTaskCmdRun::getId,v->v));
    }

    /**
     * 新增任务执行指令
     *
     * @param topCentralTaskCmdRun 任务执行指令
     * @return 结果
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean insert(TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        return super.insert(topCentralTaskCmdRun);
    }

    /**
     * 新增（批量）任务执行指令
     *
     * @param topCentralTaskCmdRunList 实体对象集合
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean insertBatch(Collection<TopCentralTaskCmdRun> topCentralTaskCmdRunList, int batchSize) {
        return super.insertBatch(topCentralTaskCmdRunList, batchSize);
    }

    /**
     * 删除 任务执行指令 根据编号
     * @param id
     * @return true 删除成功 false 删除失败
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    /**
     * 批量删除 任务执行指令 根据 编号集合
     * @param ids
     * @return true 删除成功 false 删除失败
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean deleteByIds(Collection<? extends Serializable> ids) {
        return super.deleteByIds(ids);
    }

    /**
     * 批量修改 任务执行指令 根据唯一编号
     * @param topCentralTaskCmdRunList
     * @param batchSize  更新批次数量
     * @return true 修改成功 false 修改失败
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean updateBatchById(Collection<TopCentralTaskCmdRun> topCentralTaskCmdRunList, int batchSize) {
        return super.updateBatchById(topCentralTaskCmdRunList, batchSize);
    }

    /**
     * 修改 任务执行指令
     * @param  topCentralTaskCmdRun
     * @param updateWrapper
     * @return
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean update(TopCentralTaskCmdRun topCentralTaskCmdRun, LambdaUpdateWrapper<TopCentralTaskCmdRun> updateWrapper) {
        return super.update(topCentralTaskCmdRun,updateWrapper);
    }

    /**
     * 修改任务执行指令
     *
     * @param topCentralTaskCmdRun 任务执行指令
     * @return 结果
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean updateById(TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        return super.updateById(topCentralTaskCmdRun);
    }

    /**
     * 修改任务执行指令状态 根据 id 任务执行指令
     * 
     * @param id 任务执行指令主键
     * @param state 数据状态
     * @return 结果
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean updateStateById(Integer id, State state){

        return updateById(buildTopCentralTaskCmdRunForUpdateState(id,state));
    }

    /**
     * 修改多个任务执行指令状态 根据 id 任务执行指令
     * 
     * @param ids 任务执行指令主键
     * @param state 数据状态
     * @return 结果
     */
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean updateStateByIds(Collection<Integer> ids, State state){

        List<TopCentralTaskCmdRun> updateTopCentralTaskCmdRunList = new ArrayList(ids.size());

            ids.forEach(id->updateTopCentralTaskCmdRunList.add(buildTopCentralTaskCmdRunForUpdateState(id,state)));

        return updateBatchById(updateTopCentralTaskCmdRunList);
    }

    /**
     * 处理指令任务执行
     * @param taskCmdRun
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(keyGenerator=CacheConstants.KeyGeneratorName.EHCACHE_KEY_GENERATOR_EVICT)
    @Override
    public boolean handleTaskCmdRun(@NotNull TopCentralTaskCmdRun taskCmdRun) {

        PublisherUtils.publishEvent(TaskCmdRunEvent.class,taskCmdRun, SignEnum.UPDATE);

        TopCentralTaskCmdRun taskCmdRunOfUpdate = new TopCentralTaskCmdRun();

        taskCmdRunOfUpdate.setId(taskCmdRun.getId());
        taskCmdRunOfUpdate.setTaskStatus(taskCmdRun.getTaskStatus());

        return updateById(taskCmdRunOfUpdate);
    }

    /**
     * 构建修改TopCentralTaskCmdRun 的 修改类
     * @param id 任务执行指令主键
     * @param state 数据状态
     * @return TopCentralTaskCmdRun构建的修改模型
     */
    private TopCentralTaskCmdRun buildTopCentralTaskCmdRunForUpdateState(Integer id, State state){

        TopCentralTaskCmdRun topCentralTaskCmdRun = new TopCentralTaskCmdRun();
        topCentralTaskCmdRun.setState(state);
        topCentralTaskCmdRun.setId(id);

        return topCentralTaskCmdRun;
    }

}
